package leetcode.l0606;

import leetcode.l0530.Easy_回文链表_234;

/**
 * @author Retain
 * @date 2021/6/6 14:53
 */
public class Medium_删除链表的倒数第N个结点_19 {


    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode node = removeNthFromEnd(node1, 3);
        while (node != null) {
            System.out.print(node.val+" ");
            node = node.next;
        }
    }
    /**
     * 第一反应使用快慢指针
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || head.next == null) {
            return null;
        }
        // 记录length，处理删除头节点情况。
        int length = 1;
        int m = n;
        // 记录被删除结点的前一结点
        ListNode preSlow = head;
        // 被删除结点
        ListNode slow = head;
        // 快指针遍历结束时，慢指针即为被删除的结点
        ListNode fast = head;
        //  先初始化快指针
        while (m > 1) {
            fast = fast.next;
            m--;
            length++;
        }
        // 一起移动
        while (fast.next != null) {
            preSlow = slow;
            slow = slow.next;
            fast = fast.next;
            length++;
        }
        // 删除头节点，返回头节点的next即可
        if (length == n) {
            return head.next;
        }
        preSlow.next = slow.next;
        return head;
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
